package com.mvc.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.action.BaseAction;
import com.mvc.bean.BaseBean;
import com.mvc.bean.XmlBean;
import com.mvc.util.FullBean;

public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public BaseServlet() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException  {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String forward="";
			String path=getPath(request.getServletPath());
			Map<String, XmlBean> map=(Map<String, XmlBean>)request.getSession().getServletContext().getAttribute("initData");
			XmlBean bean = map.get(path);
			if(bean!=null && bean.getBeanClass()!=null){
				BaseBean baseBean=FullBean.full(bean.getBeanClass(), request);
				Class action=Class.forName(bean.getActionClass());
				BaseAction ba=(BaseAction)action.newInstance();
				forward=ba.execute(request, response, baseBean, bean.getActionForward());
			}
			RequestDispatcher dis = request.getRequestDispatcher(forward);
			dis.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private String getPath(String servletPath) {
		return servletPath.split("\\.")[0];
	}
}
